package com.tom.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.tom.common.exception.ServiceException;
import com.tom.common.resp.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        String errMsg=null;
        //处理后端验证失败产生的异常
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            errMsg=exception.getBindingResult().getFieldError().getDefaultMessage();
        }
        //HTTP请求类型不正确的异常
        else if (e instanceof HttpRequestMethodNotSupportedException) {
            errMsg="Web方法不支持当前的请求类型";
        }
        //缺少必须提交的表单数据
        else if (e instanceof HttpMessageNotReadableException) {
            errMsg="缺少提交的数据";
        }
        //处理业务异常
        else if (e instanceof ServiceException) {
            log.error("执行异常", e);
            ServiceException exception = (ServiceException) e;
            errMsg=exception.getMsg();
        }
        //处理其余的异常
        else {
            log.error("执行异常", e);
            errMsg="执行异常";
        }
        return R.error(errMsg);
    }


    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NotLoginException.class)
    public R unLoginHandler(Exception e) {
        return R.error(e.getMessage());
    }


}
